package com.ctvit.cch.core.task;

import com.ctvit.cch.ai.pojo.dto.GenerateScriptDTO;
import com.ctvit.cch.ai.pojo.vo.GenerateScriptVO;
import com.ctvit.cch.ai.service.ILlmService;
import com.ctvit.cch.core.enums.GenerateStatusEnum;
import com.ctvit.cch.core.pojo.domain.CreativeScriptScene;
import com.ctvit.cch.core.pojo.vo.creative.CreativeScriptDesignListVO;
import com.ctvit.cch.core.service.ICreativeScriptDesignService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

/**
 * 脚本设计任务
 *
 * @author heyingcheng
 * @date 2025/10/29
 */
@Slf4j
@Component("creativeScriptDesignTask")
@ConditionalOnProperty(name = "cch.core.task.script-design.enabled", havingValue = "true")
public class CreativeScriptDesignTask implements SchedulingConfigurer {

    private static final String CRON_EXPRESSION = "0/5 * * * * ?";

    @Resource
    private ICreativeScriptDesignService creativeScriptDesignService;

    @Resource
    private ILlmService llmService;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(this::execute, triggerContext -> {
            CronTrigger trigger = new CronTrigger(CRON_EXPRESSION);
            return trigger.nextExecution(triggerContext);
        });
    }

    public void execute() {
        log.debug("执行脚本设计任务-开始");

        List<CreativeScriptDesignListVO> scriptDesignList = creativeScriptDesignService
                .listByGenerateStatus(GenerateStatusEnum.QUEUED.name());
        for (CreativeScriptDesignListVO scriptDesignListVo : scriptDesignList) {
            try {
                generateScriptDesign(scriptDesignListVo);
            } catch (Exception e) {
                log.error("生成场景设计任务异常, scriptId:[{}]", scriptDesignListVo.getScriptId(), e);
            }
        }

        log.debug("执行脚本设计任务-结束");
    }

    private void generateScriptDesign(CreativeScriptDesignListVO vo) {
        String topicId = vo.getTopicId();
        String scriptId = vo.getScriptId();

        creativeScriptDesignService.updateGenerateStatus(scriptId, GenerateStatusEnum.QUEUED.name(),
                GenerateStatusEnum.ING.name());

        GenerateScriptDTO generateScriptDTO = new GenerateScriptDTO();
        generateScriptDTO.setScriptTitle(vo.getScriptTitle());
        generateScriptDTO.setScriptTheme(vo.getScriptTheme());
        generateScriptDTO.setScriptDescription(vo.getScriptDescription());
        generateScriptDTO.setScriptContent(vo.getScriptContent());
        generateScriptDTO.setDurationRange(vo.getDurationRange());
        generateScriptDTO.setAspectRatio(vo.getAspectRatio());
        generateScriptDTO.setToneStyle(vo.getToneStyle());
        generateScriptDTO.setCopyStructure(vo.getCopyStructure());

        List<GenerateScriptVO> scripScenes = Collections.emptyList();

        try {
            scripScenes = llmService.generateScript(generateScriptDTO);
        } catch (Exception e) {
            log.error("生成脚本场景任务异常, scriptId:[{}]", scriptId, e);
            creativeScriptDesignService.updateGenerateStatus(scriptId, GenerateStatusEnum.ING.name(),
                    GenerateStatusEnum.FAILURE.name());
        }

        int size = scripScenes.size();
        List<CreativeScriptScene> records = new ArrayList<>(size);
        for (int i = 0; i < size; i++) {
            GenerateScriptVO scriptScene = scripScenes.get(i);

            CreativeScriptScene record = new CreativeScriptScene();
            record.setScriptId(scriptId);
            record.setTopicId(vo.getTopicId());
            record.setSceneIndex(i + 1);
            record.setSceneName(scriptScene.getSceneName());
            record.setSceneDuration(scriptScene.getSceneDuration());
            record.setSceneDescription(scriptScene.getSceneDescription());
            record.setEventDescription(scriptScene.getEventDescription());
            record.setCharacters(CollectionUtils.emptyIfNull(scriptScene.getCharacters()));
            record.setCharacterDialogue(scriptScene.getCharacterDialogue());
            record.setSidebarContent(scriptScene.getSidebarContent());

            records.add(record);
        }

        creativeScriptDesignService.updateGenerateStatus(scriptId, topicId, GenerateStatusEnum.SUCCESS.name(), records);
    }

}
